// 验证是否有登录，没有登录就跳转到登录页面
(async function () {
    const doms = {
        aside: {
            nickname: document.querySelector("#nickname"),
            loginId: document.querySelector("#loginId"),
        },
        close: document.querySelector(".icon-close"),
        txtMsg: document.querySelector("#txtMsg"),
        form: document.querySelector(".msg-container"),
        chatContainer: document.querySelector(".chat-container"),
    }
    const res = await API.profile()
    const user = await res.data
    if (!user) {
        alert("用户未登录或登录已失效，请重新登录")
        location.href = './login.html'
        return
    }
    function setUserInfo() {
        doms.aside.nickname.innerText = user.nickname
        doms.aside.loginId.innerText = user.loginId
    }

    function formatTime(timestamp, format) {
        let time = new Date(timestamp)
        let year = time.getFullYear()
        let month = (time.getMonth() + 1).toString().padStart(2, '0')
        let day = time.getDate().toString().padStart(2, '0')
        let hour = time.getHours().toString().padStart(2, '0')
        let minute = time.getMinutes().toString().padStart(2, '0')
        let second = time.getSeconds().toString().padStart(2, '0')
        return format.replace(/YYYY/, year).replace(/MM/, month).replace(/DD/, day).replace(/hh/, hour).replace(/mm/, minute).replace(/ss/, second)
    }
    //根据消息对象，将其添加到页面中
    function addChat(chatInfo) {
        let html = ''
        const div = document.createElement("div")
        div.className = "chat-item"
        if (chatInfo.from === user.loginId) {
            div.classList.add("me")
            div.innerHTML = `
            <img class="chat-avatar" src="./asset/avatar.png" />
            <div class="chat-content">${chatInfo.content}</div>
            <div class="chat-date">${formatTime(chatInfo.createdAt, 'YYYY-MM-DD hh:mm:ss')}</div>
            `
        } else {
            div.innerHTML = `<img class="chat-avatar" src="./asset/robot-avatar.jpg" />
            <div class="chat-content">${chatInfo.content}</div>
            <div class="chat-date">${formatTime(chatInfo.createdAt, 'YYYY-MM-DD hh:mm:ss')}</div>
            `
        }
        doms.chatContainer.appendChild(div)
        scrollBottom()
    }
    //加载历史记录
    async function loadHistory() {
        const res = await API.getHistory()
        data = await res.data
        data.forEach(chatInfo => {
            addChat(chatInfo)
        });
    }
    // 滚动条滚动到最后
    function scrollBottom() {
        doms.chatContainer.scrollTop = doms.chatContainer.scrollHeight
    }
    //发送消息
    async function sendChat() {
        console.log('test')
        let content = doms.txtMsg.value.trim()
        if (!content) return
        addChat({
            from: user.loginId,
            to: null,
            createdAt: Date.now(),
            content
        })
        scrollBottom()
        doms.txtMsg.value = ''
        const res = await API.sendChat(content)
        addChat({
            from:null,
            to:user.loginId,
            ...res.data
        })
    }
    function init() {
        setUserInfo()
        loadHistory()
    }
    function bindEvent() {
        doms.form.onsubmit = function(e){
            e.preventDefault()
            sendChat()
        }
        // 账号退出
        doms.close.onclick = () => {
            API.exit()
            location.href = './login.html'
        }
    }
    init()
    bindEvent()

})()